import React, { PureComponent, Fragment } from 'react'
import { connect } from 'dva'
import {
  Button,
  Card,
  Tabs,
  Table,
  Divider,
  Popconfirm,
  Spin,
  Badge,
  Modal,
  message,
  Row,
  Switch,
  Radio,
  Form,
  Cascader
} from 'antd'
import { routerRedux } from 'dva/router'
import Search from '@/components/Search'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import goodsService from '@/services/goods'
import template from '@/services/template'
import CopyToClipboard from '@/components/CopyToClipboard'
import moment from 'moment'
import addressList from '@/assets/provinceAndCityAndArea.json'
const auditState = ['审核中', '审核拒绝', '审核通过']
const tabList = [
  {
    key: '0',
    tab: '全部商品',
    prop: 'allCounts',
    filterKey: '',
    filterStatus: ''
  },
  {
    key: '1',
    tab: '审核通过',
    prop: 'putOnCounts',
    filterKey: 'type',
    filterStatus: '1'
  },
  {
    key: '2',
    tab: '审核拒绝',
    prop: 'notPutOnCounts',
    filterKey: 'type',
    filterStatus: '2'
  },
  {
    auditState: 3,
    key: '3',
    prop: 'pendingCounts',
    tab: '待审核',
    filterKey: 'auditState',
    filterStatus: '0'
  },
  {
    auditState: 4,
    prop: 'notPassCounts',
    key: '4',
    tab: '未通过',
    filterKey: 'auditState',
    filterStatus: '1'
  } // {
  //   key: '0',
  //   tab: '回收站',
  // },
]


@connect(({ goodsList, loading, template }) => ({
  ...template,
  ...goodsList,
  loading: loading.models.goodsList,
}))
class List extends PureComponent {
  state = {
    tableData: [],
    AuditDetail: [],
    loading: true,
    tabType: '0',
    auditVisible: false,
    current: 1,
    pageNumber: 1,
    pageSize: 10,
    total: 0,
    counts: {},
    categories: [],
    modalTableCurrent: 1,
    modalPageSize: 10,
    modalTotal: 0,
    filter: {},
    isModalOpen: false, //关联商品模态框
    associatedShopList: [],
    radioVal: '',
    id: 0,
    loadingFlg: false,
    addressData: [],
    selectedRowKeys: [],
    cityData: [],
    selectK: [],
    valueV: []
    
  }

  columns = this.getColumns()

  map = {
    'FREE': '包邮',
    'PAY': '到付',
    'SELF': '自提',
  }

  auditColumns = [
    {
      title: '审核时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center'
    },
    {
      title: '审核人员',
      dataIndex: 'operator',
      width: 120
    },
    {
      title: '审核结果',
      dataIndex: 'auditStatus',
      width: 120,
      render: text => {
        const _text = auditState[text]
        if (text === 1) {
          return (
            <span className="red">
              <Badge status="error" />
              未通过
            </span>
          )
        }
        return _text
      }
    },
    {
      title: '反馈详情',
      dataIndex: 'feedBack'
    }
  ]

  // search = {}

  componentDidMount() {
    console.log(this.search.props.handleFilter())
    this.getTabCount()
    this.findCategories()
  }

  getColumns() {
    let colunms = []
    if (localStorage.getItem('email') == '15277008888') {
      colunms = [
        {
          title: '商品编号',
          dataIndex: 'productId',
          width: 160,
          align: 'center',
          className: 'table-cell-goodsnumber',
          render: text => <CopyToClipboard text={text} />
        },
        {
          title: '商品图片',
          dataIndex: 'src',
          render: text => (
            <img src={text} alt="" style={{ width: 60, height: 60 }} />
          )
        },
        {
          title: '商品名称',
          dataIndex: 'name'
        },
        {
          title: '商品类目',
          dataIndex: 'opeCategoryStr',
          width: 160
        },
        {
          title: '状态',
          dataIndex: 'status',
          align: 'center',
          width: 90,
          key: 'status',
          render: text => {
            const success = text === 1
            const status = success ? 'success' : 'default'
            const badgeText = success ? '已上架' : '已下架'
            return <Badge status={status} text={badgeText} />
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 120
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 80,
          render: (_, record) => (
            <div>
              <a onClick={() => this.gotoDetail(record.id)}>修改</a>
            </div>
          )
        }
      ]
    } else {
      colunms = [
        {
          title: '商品编号',
          dataIndex: 'productId',
          align: 'center',
          className: 'table-cell-goodsnumber',
          render: text => <CopyToClipboard text={text} />
        },
        {
          title: '商品图片',
          dataIndex: 'src',
          align: 'center',
          render: text => (
            <img src={text} alt="" style={{ width: 100, height: 100 }} />
          )
        },
        {
          title: '商品名称',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '商品类目',
          dataIndex: 'opeCategoryStr',
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'status',
          align: 'center',
          key: 'status',
          render: text => {
            const success = text === 1
            const status = success ? 'success' : 'default'
            const badgeText = success ? '已上架' : '已下架'
            return <Badge status={status} text={badgeText} />
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center'
        },
        {
          title: '审核状态',
          dataIndex: 'auditState',
          align: 'center',
          key: 'auditState',
          render: (text, record) => {
            const _text = auditState[text]
            return (
              <div>
                {_text}
                <br />
                {_text ? (
                  <a onClick={() => this.handleAuditModal(record)}>审核详情</a>
                ) : null}
              </div>
            )
          }
        },
        {
          title: '商品隐藏状态',
          dataIndex: 'hideFlag',
          align: 'center',
          render: (text, record) => {
            return (
              <>
                {/* <span>{text !== 1 ? '当前可见' : '已隐藏'}</span> */}
                <span>{text ? '已隐藏' : '当前可见'}</span>
                &nbsp;
                <Switch
                  checked={!text}
                  onChange={() => this.handleHide(record)}
                />
              </>
            )
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 300,
          align: 'center',
          render: (_, record) => (
            record.auditState != 1 && <Row type="flex">
              {/* <Button
                size="small"
                type="primary"
                onClick={() => this.gotoDetail(record.id)}
              >
                修改
              </Button>
              <Divider type="vertical"/>
              <Button
                size="small"
                type="primary"
                onClick={() => this.handleCopy(record)}
              >
                复制
              </Button>
              <Divider type="vertical"/> */}
              <Popconfirm
                title="是否删除该商品？"
                disabled={record.association == 1}
                onConfirm={() => this.handleDelete(record)}
              >
                <Button size="small" type="danger" disabled={record.association == 1}>
                  删除
                </Button>
              </Popconfirm>
              <Divider type="vertical"/>
                <Button size="small" type="danger" onClick={() => this.showModal(record)} disabled={record.association == 1 || record.auditState != 2}>
                  { record.association == 1 ? '已添加' : '添加商品' }
                </Button> 
                
              {/* <Popconfirm
                title="是否确认审核通过？"
                onConfirm={() => this.auditFn(record, 2)}
                onCancel={() => this.auditFn(record, 1)}
                disabled={record.auditState == 2}
              >
                <Button size="small" type="danger" disabled={record.auditState}>
                    {auditState[record.auditState]}
                </Button>
              </Popconfirm> */}
                {/* {record?.shopDto && 
                  <>
                    <Divider type="vertical"/>
                    <Popconfirm
                      title="是否解绑？"
                      description="Are you sure to delete this task?"
                      onConfirm={() => {this.upDateBind(record)}} 
                      okText="是"
                      cancelText="否"
                    >
                      <Button size="small" type="danger">
                        解绑
                      </Button>
                    </Popconfirm>
                  </>
                } */}
            </Row>
          )
        }
      ]
    }
    return colunms
  }

   asColumns = [ 
    {
      title: '手机号码',
      dataIndex: 'telephone',
      key: 'telephone',
    },
    {
      title: '收货地址',
      dataIndex: 'street',
      key: 'street',
    },
    {
      title: '收货人',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '退货快递',
      dataIndex: 'freightType',
      key: 'freightType',
      render: (text, record) => {
        return this.map[text]
      }
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
  ];

  handleRadioChange = (e, record) => {
    const newSelectedRowKeys = e.target.checked
      ? [...this.state.selectedRowKeys, record.id]
      : this.state.selectedRowKeys.filter((key) => key !== record.id);
    this.setState({
      selectedRowKeys: newSelectedRowKeys,
    })
  }; //归还地址单选

  
  auditFn = async (record, state) => {
    const { dispatch } = this.props
    await dispatch({
        type: 'template/auditProductTemplate',
        payload: {
            id: record.id,
            auditState: state
        }
    })
  } //审核通过
  upDateBind = async (record) => {
    const { dispatch } = this.props
    await dispatch({
      type: 'template/updateProductBindShopId',
      payload: {
        id: record.id,
        // bindShopId: record.shopDto.shopId
      }
    })
    message.success('解绑成功')
    this.initData()
  }   

  findCategories = () => {
    goodsService.findCategories().then(res => {
      this.setState({
        categories: res || []
      })
    })
  }

  handleDelete = record => {
    template
      .deleteProductTemplate({
        id: record.id
      })
      .then(res => {
        message.success('删除成功')
        this.handleFilter()
      })
  }

  handleHide = record => {
    goodsService
      .busUpdateProductByRecycleHide({
        id: record.id,
        hideFlag: record.hideFlag === 1 ? 0 : 1
      })
      .then(res => {
        message.success('修改成功')
        this.handleFilter()
      })
  }

  handleCopy = record => {
    goodsService
      .busCopyProduct({
        productId: record.productId
      })
      .then(res => {
        message.success('复制成功')
        this.handleFilter()
      })
  }

  gotoDetail = id => {
    const { dispatch } = this.props
    dispatch(
      routerRedux.push({
        pathname: `/template/list/detail/${id}`
      })
    )
  }

  handleUpDown = record => {
    const { dispatch, queryInfo } = this.props
    dispatch({
      type: 'goodsList/busUpdateProductByUpOrDown',
      payload: record,
      callback: () => {
        this.setDispatch(queryInfo)
      }
    })
  }

  tabChange = type => {
    console.log(type)
    this.setState(
      {
        tabType: type
      },
      () => {
        this.handleFilter()
      }
    )
  }

  handleAuditModal = record => {
    this.selectExamineProductAuditLog(record)
    this.setState({
      auditVisible: true
    })
  }

  close = () => {
    this.setState({
      auditVisible: false
    })
  }

  selectExamineProductAuditLog = record => {
    const { modalTableCurrent, modalPageSize } = this.state
    goodsService
      .selectExamineProductAuditLog({
        id: record.id,
        itemId: record.productId,
        pageNumber: modalTableCurrent,
        pageSize: modalPageSize
      })
      .then(res => {
        this.setState({
          AuditDetail: res.records || [],
          modalTotal: res.total,
          modalTableCurrent: res.current
        })
      })
  }

  getTabCount = () => {
    goodsService.selectBusinessPrdouctCounts().then(res => {
      this.setState({
        counts: res
      })
    })
  }

  initData = () => {
    const { pageNumber, pageSize, filter, tabType } = this.state
    const item = tabList[tabType]
    if (item.filterKey) {
      filter[item.filterKey] = item.filterStatus
    }
    let payload = {
      pageNumber,
      pageSize,
      type: '1', // 默认已上架
      isDelete: false,
      ...filter
    }
    this.setState(
      {
        loading: true
      },
      () => {
        template
          .selectBusinessPrdouctTemplate({
            ...payload
          })
          .then(res => {
            this.setState({
              tableData: res.records,
              total: res.total,
              loading: false,
              current: res.current
            })
          })
      }
    )
  }

  handleFilter = (data = {}) => {
    const { type } = data
    if (data.queryType && data.queryType === '分页') {
      this.initData()
    } else {
      this.setState(
        {
          pageNumber: this.state.pageNumber,
          pageSize: this.state.pageSize,
          filter: data
        },
        () => {
          this.initData()
        }
      )
    }
  }

  //分页，下一页
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber: pageNumber
      },
      () => {
        this.handleFilter({ queryType: '分页' })
      }
    )
  }

  showTotal = () => {
    return `共有${this.state.total}条`
  }

  //切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState({ pageSize: pageSize ,pageNumber:1}, () => {
      this.handleFilter({ queryType: '分页' })
    })
  }

  handleExportData = filter => {
    if (filter.createDate && filter.createDate.length > 1) {
      filter.createTimeStart = moment(filter.createDate[0]).format(
        'YYYY-MM-DD HH:mm:ss'
      )
      filter.createTimeEnd = moment(filter.createDate[1]).format(
        'YYYY-MM-DD HH:mm:ss'
      )
    }
    goodsService.exportBusinessPrdouct(filter).then(res => {
      // downloadFile(res)
      location.href = res
    })
  }


     showModal = async (record) => {
      const { dispatch } = this.props 
      const res = await dispatch({
        type: 'template/selectShopRuleAndGiveBackByShopId',
      }); //获取归还地址
      // const city = await dispatch({
      //   type: 'template/selectDistrict', 
      // })
      // console.log(city, 'ressssssssssssss');
      
      // this.setState(() => ({
      //   loadingFlg: true
      // }))
      // const bak = await dispatch({
      //   type: 'template/selectAllShop',
      //   payload: {},
      // }) 
      this.setState(() => ({
        addressData: res, //归还地址
        id: record, 
        // associatedShopList: bak.data, 
      }))
      // console.log(this.state.associatedShopList, 'rrrr');
       
      this.setState({
        isModalOpen: true
      })  
    }; //打开弹窗

     handleOk = async () => {
       console.log(this.state.cityData.length, this.state.selectedRowKeys.length);
      if(this.state.cityData.length == 0 || this.state.selectedRowKeys.length == 0) {
        message.error('请完整填入')
        return
      } else {
      const { dispatch } = this.props 
      await dispatch({
        type: 'template/insertProductTemplateAddress',
        payload: {
          id: this.state.id.id,
          productId: this.state.id.productId,
          // bindShopId: this.state.radioVal
          province: this.state.cityData[0],
          city: this.state.cityData[1],
          addIds: [this.state.selectedRowKeys[0].id],
          shopId: localStorage.getItem('shopId')
        },
      })
      this.setState({
        // radioVal: undefined,
        addressData: null, //归还地址
        id: null, 
        isModalOpen: false, 
        cityData: [],
        selectK: [],
        selectedRowKeys: [],
        valueV: []
      })
      this.initData()
      }
   
    }; //确认弹窗

     handleCancel = () => {
      console.log('关闭');
      
      this.setState({
        isModalOpen: false,
        addressData: null, //归还地址
        id: null, 
        isModalOpen: false, 
        cityData: [],
        selectedRowKeys: []
      })
    }; //关闭弹窗



     rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        this.setState({
          selectedRowKeys: selectedRows,
          selectK: selectedRowKeys
        })
      }
    };

  render() {
    const {
      loading,
      current,
      total,
      categories = [],
      tabType,
      auditVisible,
      AuditDetail,
      tableData,
      counts,
      modalPageSize,
      modalTotal,
      modalTableCurrent
    } = this.state
    const options = [{ field: 'categoryIds', options: categories }]

    return (
      <PageHeaderWrapper title={false} className="nav-tab">
        {/*<Tabs activeKey={tabType} onChange={this.tabChange}>*/}
        {/*   {tabList.map(tab => (*/}
        {/*     <TabPane tab={`${tab.tab}(${counts[tab.prop]})`} key={tab.key} />*/}
        {/*   ))}*/}
        {/* </Tabs>*/}
        <Spin spinning={loading}>
          <Card bordered={false}>
            <Search
              needExport
              needReset
              source={'商品列表'}
              exportData={this.handleExportData}
              options={options}
              ref={ref => (this.search = ref)}
              handleFilter={this.handleFilter}
            />
          </Card>
          <Card bordered={false}>
            <Row
              style={{ marginBottom: 20 }}
              className="ds-inline-block"
              onClick={() => this.gotoDetail('add')}
            >
              <Button type="primary">新增模板</Button>
            </Row>
            <Table
              rowKey="id"
              bordered
              columns={this.columns}
              dataSource={tableData}
              pagination={{
                current: current,
                total: total,
                onChange: this.onChange,
                showTotal: this.showTotal,
                showQuickJumper: true,
                pageSizeOptions: ['5', '10', '20'],
                showSizeChanger: true,
                onShowSizeChange: this.onShowSizeChange
              }}
            />
          </Card>
        </Spin>
        <Modal
          title="审核详情"
          visible={auditVisible}
          footer={null}
          onCancel={this.close}
          width={900}
        >
          <Card bordered={false}>
            <Table
              rowKey="id"
              columns={this.auditColumns}
              dataSource={AuditDetail}
              pagination={{
                current: modalTableCurrent,
                total: modalTotal,
                onChange: this.onChange,
                showTotal: this.showTotal,
                showQuickJumper: true,
                pageSizeOptions: ['5', '10', '20'],
                showSizeChanger: true,
                onShowSizeChange: this.onShowSizeChange
              }}
            />
          </Card>
        </Modal>
        <Modal title="请选择地址" visible={this.state.isModalOpen} onOk={this.handleOk} onCancel={this.handleCancel} width={1000}> 
            <Cascader value={this.state.valueV} options={addressList} placeholder="请选择" 
              onChange={(e) => {this.setState({cityData: e, valueV: e})}}
            /> 
            <Table
              style={{marginTop: 20}}
              rowSelection={{
                  type: 'radio',
                  ...this.rowSelection,
                  selectedRowKeys: this.state.selectK,
              }}
              dataSource={this.state.addressData}
              columns={this.asColumns}
              rowKey={(record) => record.key}
              pagination={false} // 禁用分页 
            />  
        {/* <Radio.Group 
          onChange={(e) => {this.setState({radioVal: e.target.value});}} 
          value={this.state.radioVal}
        >
          {this.state.associatedShopList.length && (
              this.state.associatedShopList.map((item, index) => {
                return <Row>
                  <Radio value={item.shopId}/>{item.name}
                </Row>
              })
            )}
        </Radio.Group> */}
      </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default List
